package space.xxhui.messageconverter;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;
import space.xxhui.POJO.User;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * Created by hui on 2017/7/18.
 */
public class MyMessageConverter extends AbstractHttpMessageConverter<User> {

    public MyMessageConverter() {
        super(new MediaType("application", "x-wisely", Charset.forName("utf-8")));
    }

    protected boolean supports(Class<?> aClass) {
        return User.class.isAssignableFrom(aClass);
    }

    protected User readInternal(Class<? extends User> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        String temp = StreamUtils.copyToString(httpInputMessage.getBody(), Charset.forName("utf-8"));
        String[] tempArray = temp.split("-");
        User user = new User();
        for (String t : tempArray) {
            System.out.println(t);
        }
        user.setName(tempArray[0]);
        user.setPwd(tempArray[1]);
        return user;
    }

    protected void writeInternal(User user, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
        httpOutputMessage.getBody().write(user.toString().getBytes());
    }
}
